package com.itmuch.contentcenter.configuration;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.util.CollectionUtils;

/**
 * @author caiqian
 * @date 2021/5/7 17:36
 */
@Slf4j
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {

  @Autowired
  private NacosDiscoveryProperties nacosDiscoveryProperties;

  @Override
  public void initWithNiwsConfig(IClientConfig iClientConfig) {

  }

  @Override
  public Server choose(Object key) {

    try {
      //拿到配置文件中的集群名称, 如果BJ
      String clusterName = this.nacosDiscoveryProperties.getClusterName();

      BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();

      //想要请求的微服务的名称
      String name = loadBalancer.getName();

      //拿到服务的相关api
      NamingService namingService = this.nacosDiscoveryProperties.namingServiceInstance();

      // 1找到指定服务的所有实例 A
      List<Instance> instances = namingService.selectInstances(name, true);

      // 2 过滤出相同集群下的所有实例 B
      List<Instance> sameClusterInstances = instances.stream()
          .filter(instance -> Objects.equals(instance.getClusterName(), clusterName))
          .collect(Collectors.toList());

      List<Instance> instanceTobeChoose = new ArrayList<>();

      // 3 如果B为空,就用A
      if (CollectionUtils.isEmpty(sameClusterInstances)) {
        instanceTobeChoose = instances;
        log.warn("发生的跨集群的服务调用, name={},cluster={},instance={}",
            name, clusterName, instances);
      } else {
        instanceTobeChoose = sameClusterInstances;
      }

      // 4 基于权重的负载均衡算法, 返回一个实例
      Instance instance = ExtendBalance.getHostByRandomWeight2(instanceTobeChoose);
      log.info("选择的实例是, port={},instance={}",instance.getPort(),instance);

    } catch (NacosException e) {
      log.error("发生异常:", e);
    }

    return null;
  }

  static class ExtendBalance extends Balancer{
    public static Instance getHostByRandomWeight2(List<Instance> hosts){
      return getHostByRandomWeight(hosts);
    }
  }
}
